package com.common.spring;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.DesUtils;
import com.common.StringUtils;
import com.common.annotation.RequestCheck;
import com.common.db.RedisUtils;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.model.UserTypeEnum;
import com.model.supply.SupplyUserModel;
import com.model.sys.SysUser;

//import net.sf.json.JSONArray;

/**
 * @author tfj 2014-8-1
 */
public class CommonInterceptor extends HandlerInterceptorAdapter {
	static final Logger logger = LoggerFactory.getLogger(CommonInterceptor.class);

	@Autowired
	private RedisUtils redisUtils;

	private void initRes(JSONObject res) {
		JSONArray array = new JSONArray();
		res.put("code", HttpStatus.TOKEN_INVALID_CODE);
		res.put("msg", HttpStatus.TOKEN_INVALID_MESSAGE);
		res.put("data", null);
		res.put("rows", array);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		String requestUri = request.getRequestURI();
		logger.info("url:{}", requestUri);
		String contextPath = request.getContextPath();
		String currentUrlString = request.getHeader("currenturl");
		if (StringUtils.isNotNull(currentUrlString)) {
			currentUrlString = currentUrlString.substring(contextPath.length() + 1, currentUrlString.length());
		}

		String activeProfile = request.getSession().getServletContext().getInitParameter("spring.profiles.active");

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		RequestCheck requestCheck = method.getAnnotation(RequestCheck.class);
		JSONObject res = new JSONObject();
		if (requestUri.contains("/api")) {
			SysUser sysUser = null;
			SupplyUserModel supplyUserModel = null;
			String tokenString = "";
			try {
				String tokenTemp = request.getHeader("token");
				if (StringUtils.isNullOrEmpty(tokenTemp)) {
					tokenTemp = request.getParameter("token");
				}
				tokenString = DesUtils.decrypt(tokenTemp);
			} catch (Exception e1) {
				logger.error("url:{},token:{}", requestUri, tokenString);
				initRes(res);
				response.setContentType("application/json; charset=UTF-8");
				try {
					response.getWriter().print(res);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.error("token=null:", requestUri);
					logger.error(e.getMessage());
				}
				return false;
			}
			if (!StringUtils.isNotNull(tokenString)) {
				initRes(res);
				response.setContentType("application/json; charset=UTF-8");
				try {
					response.getWriter().print(res);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.error(activeProfile);
					logger.error("token为空:{}", e.getMessage());
				}
				return false;
			}
			String[] tokenStrings = tokenString.split(",");
			if (!StringUtils.isNotNull(tokenString) || tokenStrings.length != 3) {
				initRes(res);
				response.setContentType("application/json; charset=UTF-8");
				try {
					response.getWriter().print(res);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.error("tokenString为空:{}", e.getMessage());
				}
				return false;
			}
			String userTypeString = tokenStrings[2];
			// 是否超时
//			long time = Long.parseLong(tokenStrings[1]);
//			if (System.currentTimeMillis() - time > Global.PC_BACKGROUND_TOKEN_EXPIRE) {
//				res.put("code", HttpStatus.TOKEN_INVALID_CODE);
//				res.put("msg", HttpStatus.TOKEN_INVALID_MESSAGE);
//				response.setContentType("application/json; charset=UTF-8");
//				response.getWriter().print(res);
//				return false;
//			}
			// 内部用户
			if (userTypeString.equals(UserTypeEnum.XYUser.getValue())) {
				sysUser = (SysUser) redisUtils.get(Global.REDIS_USER_PREFIX + userTypeString + "-" + tokenStrings[0]);
				if (sysUser == null) {
					initRes(res);
					response.setContentType("application/json; charset=UTF-8");
					try {
						response.getWriter().print(res);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						logger.error("sysUser为空:{}", e.getMessage());
					}
//				request.getRequestDispatcher("/index.jsp").forward(request, response);
					return false;
				} else {
					request.getSession().setAttribute("userType", userTypeString);
					request.getSession().setAttribute("sysUser", sysUser);
					request.getSession().setMaxInactiveInterval(Global.PC_BACKGROUND_TOKEN_EXPIRE);
					redisUtils.expire(Global.REDIS_USER_PREFIX + userTypeString + "-" + tokenStrings[0],
							Global.PC_BACKGROUND_TOKEN_EXPIRE);
					return true;
				}
			} else if (userTypeString.equals(UserTypeEnum.SupplyUser.getValue())) {// 外部用户
				supplyUserModel = (SupplyUserModel) redisUtils
						.get(Global.REDIS_USER_PREFIX + userTypeString + "-" + tokenStrings[0]);
				if (supplyUserModel == null) {
					initRes(res);
					response.setContentType("application/json; charset=UTF-8");
					try {
						response.getWriter().print(res);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						logger.error("supplyUserModel为空:{}", e.getMessage());
					}
					return false;
				} else {
					request.getSession().setAttribute("userType", userTypeString);
					request.getSession().setAttribute("supplyUserModel", supplyUserModel);
					request.getSession().setMaxInactiveInterval(Global.PC_BACKGROUND_TOKEN_EXPIRE);
					redisUtils.expire(Global.REDIS_USER_PREFIX + userTypeString + "-" + tokenStrings[0],
							Global.PC_BACKGROUND_TOKEN_EXPIRE);
					return true;
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) {
		if (modelAndView != null) {
//			String pString = (String)redisUtils.get("display_permissions");
//			logger.info("pstring:{}",pString);
//			if (!StringUtils.isNotNull(pString)) {
//				SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
//				String userid = sysUser.getUserid();
//				String url = request.getServletPath();
//				if (url.length() > 0) {
//					url = url.substring(1, url.length());
//				}
//				List<String> listP = sysManageMapper.GetPermission(userid, url);
//				for (String s : listP) {
//					pString += s + ",";
//				}
//				redisUtils.set("display_permissions", pString, 1000 * 60 * 60 * 1);
//				request.getSession().setAttribute("display_permissions", pString);
//			}
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

	}

}